package com.supersit.greensproject.AsyncTask;

import android.content.Context;
import android.os.AsyncTask;
import android.os.Handler;
import android.os.Message;

import com.supersit.greensproject.DB.XUtilsDbManager;
import com.supersit.greensproject.entity.DataUpload;
import com.supersit.greensproject.resources.API;
import com.supersit.greensproject.utils.HttpXUtils;
import com.supersit.greensproject.utils.L;
import com.supersit.greensproject.utils.MyCallBack;
import com.supersit.greensproject.utils.T;
import com.supersit.greensproject.view.ShowDialog;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.xutils.DbManager;
import org.xutils.ex.DbException;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 数据上传的列表
 * Created by Administrator on 2016/8/27 0027.
 */
public class UploadDataSelectResult {
    private Context context;
    private int userId;
    private final int GET_NET_DATA_SUCCESS = 0x100;
    private final int GET_DB_DATA_SUCCESS = 0x1001;
    List<DataUpload> data = new ArrayList<>();
    List<DataUpload> serviceData = new ArrayList<>();
    private CallBackUpdate callBackUpdate;


    public UploadDataSelectResult(Context context, int userId, CallBackUpdate callBackUpdate) {
        this.context = context;
        this.userId = userId;
        this.callBackUpdate = callBackUpdate == null ? null : callBackUpdate;
    }

    /**
     * 请求服务器上指定用户的数据上报记录
     *
     * @return
     */
    public void getUploadNetData() {
        if (null != serviceData)
            serviceData.clear();
        List<DataUpload> list = null;
        final ShowDialog showDialog = new ShowDialog(context);
        String url = API.UploadDadaRecord;
        Map<String, String> map = new HashMap<>();
        map.put("userId", userId + "");
        showDialog.showLoadingDialog("正在更新数据....");
        HttpXUtils.Get(url, map, new MyCallBack<String>() {
                    @Override
                    public void onSuccess(String result) {
                        super.onSuccess(result);
                        showDialog.dismissLoadDialog();
                        {
                            try {
                                JSONArray jsonArray = new JSONArray(result);
                                if (null != jsonArray && jsonArray.length() > 0) {
                                    for (int i = 0; i < jsonArray.length(); i++) {
                                        JSONObject item = jsonArray.getJSONObject(i);
                                        int userId = item.optInt("userId") == 0 ? 0 : item.optInt("userId");
                                        int uploadDataId = item.optInt("uploadDataId") == 0 ? 0 : item.optInt("uploadDataId");
                                        String baseName = item.optString("baseName") == null ? "" : item.optString("baseName");
                                        int area = item.optInt("area") == 0 ? 0 : item.optInt("area");
                                        String baseAddreaa = item.optString("baseAddress") == null ? "" : item.optString("baseAddress");
                                        String contacts = item.optString("contacts") == null ? "" : item.optString("contacts");
                                        String tel = item.optString("tel") == null ? "" : item.optString("tel");
                                        String output = item.optString("output") == null ? "" : item.optString("output");
                                        String quarter = item.optString("quarter") == null ? "" : item.optString("quarter");
                                        String proportion = item.optString("proportion") == null ? "" : item.optString("proportion");
                                        String estimatedOutput = item.optString("estimatedOutput") == null ? "" : item.optString("estimatedOutput");
                                        String estimatedUploadDate = item.optString("estimatedUploadDate") == null ? "" : item.optString("estimatedUploadDate");
                                        int merchandise = item.optInt("merchandise") == 0 ? 0 : item.optInt("merchandise");
                                        int baseId = item.optInt("baseId");
                                        int isDelete = item.optInt("isDelete");
                                        long timeStamp = item.optLong("timeStamp");
                                        int operationsTatus = item.optInt("operationsTatus");
                                        DataUpload dataUpload = new DataUpload();
                                        dataUpload.setUserId(userId);
                                        dataUpload.setUploadDataId(uploadDataId);
                                        dataUpload.setBaseName(baseName);
                                        dataUpload.setArea(area);
                                        dataUpload.setBaseAddress(baseAddreaa);
                                        dataUpload.setContacts(contacts);
                                        dataUpload.setTel(tel);
                                        dataUpload.setOutput(output);
                                        dataUpload.setQuarter(quarter);
                                        dataUpload.setProportion(proportion);
                                        dataUpload.setEstimatedOutput(estimatedOutput);
                                        dataUpload.setEstimatedUploadDate(estimatedUploadDate);
                                        dataUpload.setMerchandise(merchandise);
                                        dataUpload.setBaseId(baseId);
                                        dataUpload.setTimeStamp(timeStamp);
                                        dataUpload.setOperationsTatus(operationsTatus);
                                        dataUpload.setIsDelete(isDelete);
                                        serviceData.add(dataUpload);
                                    }
                                    Message msg = new Message();
                                    msg.what = GET_NET_DATA_SUCCESS;
                                    handler.sendMessage(msg);
                                }
                            } catch (JSONException e) {
                                e.printStackTrace();
                                showDialog.dismissLoadDialog();
                                L.e("更新数据异常:" + e.getMessage());
                            }

                        }

                    }

                    @Override
                    public void onError(Throwable ex, boolean isOnCallback) {
                        super.onError(ex, isOnCallback);
                    }
                }

        );

    }

    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case GET_NET_DATA_SUCCESS:
                    getUploadDbData();
                    break;
                case GET_DB_DATA_SUCCESS:
                    new SaveDbTask(serviceData, context).execute();
                    break;
            }
        }
    };

    /**
     * 清除已上传过的数据
     *
     * @return
     */

    private void getUploadDbData() {
        DbManager db = XUtilsDbManager.getInstance();
        try {
            List<DataUpload> dbData = db.selector(DataUpload.class).where("isUpload", "=", 0).findAll();
            if (null != dbData)
                db.delete(dbData);
            Message msg = new Message();
            msg.what = GET_DB_DATA_SUCCESS;
            handler.sendMessage(msg);
        } catch (DbException e) {
            e.printStackTrace();
        }
    }


    /**
     * 异步线程对数据库操作
     */
    class SaveDbTask extends AsyncTask<Integer, String, Integer> {
        private List<DataUpload> list;
        private DbManager db;
        private final int SUCCESS = 0;
        private final int FAIL = 1;
        private Context context;
        private ShowDialog showDialog;


        public SaveDbTask(List<DataUpload> list, Context context) {
            this.list = list;
            this.context = context;
            this.showDialog = new ShowDialog(context);
            db = XUtilsDbManager.getInstance();
        }

        @Override
        protected void onPostExecute(Integer result) {
            super.onPostExecute(result);
            showDialog.dismissLoadDialog();
            if (result == SUCCESS) {
                if (null != callBackUpdate) {
                    callBackUpdate.onPostExecute(result);
                }
              //  T.showShort(context, "数据加载成功！");
            } else if (result == FAIL) {
                T.showShort(context, "数据加载失败！");
            } else {
                T.showShort(context, "未知异常！");
            }
        }

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            showDialog.showLoadingDialog("正在插入数据。。。");
        }

        @Override
        protected Integer doInBackground(Integer... params) {
            try {
                for (DataUpload du : list) {
                    db.saveBindingId(du);
                }
                return SUCCESS;
            } catch (DbException e) {
                e.printStackTrace();
            }
            return FAIL;
        }
    }

    public interface CallBackUpdate {
        public void onPostExecute(Integer result);
    }
}
